package cn.wolfcode.luowowo.website.interceptor;

import cn.wolfcode.luowowo.cache.service.IUserInfoCacheService;
import cn.wolfcode.luowowo.common.util.Consts;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.RequiredLogin;
import com.alibaba.fastjson.JSON;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//检查登录的拦截器
@SpringBootConfiguration
public class CheckLoginInterrceptor extends HandlerInterceptorAdapter{

    @Reference
    private IUserInfoCacheService userInfoCacheService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      //1.静态资源直接方向性,当hanler对象是HandlerMethod类型是表示当前访问的Conroller
        if (!(handler instanceof HandlerMethod)){
            return true;
        }
        //2.不需啊哟登录的资源直接放行
        HandlerMethod hm= (HandlerMethod) handler;
        if(!hm.hasMethodAnnotation(RequiredLogin.class)){
            return true;
        }
        //3取出当前登入的用户
        HttpSession session = request.getSession();
        Object user = session.getAttribute(Consts.USER_INFO);
        if(user!=null){
            return true;
        }
        //4从redis中去登录用户
        Cookie[] cs = request.getCookies();
        if(cs!=null){
            for(Cookie c:cs){
                if(c.getName().equals(Consts.USER_INFO_TOKEN)){
                    //取出token
                    String token = c.getValue();
                    String userInfo = userInfoCacheService.getVerifycode(token);
                    if(userInfo!=null){
                        //存userInfo入session中
                        session.setAttribute(Consts.USER_INFO, JSON.parseObject(userInfo, UserInfo.class));
                    }
                }
            }
        }
        //没有登录回到登录界面
        response.sendRedirect("/login.html");
        return false;
    }
}
